//
//  CategoryMacro.h
//  Project
//
//  Created by  CarlsonLee on 2018/12/7.
//  Copyright © 2018年 YANJING. All rights reserved.
//

#import <sys/time.h>
#import <pthread.h>

#ifndef CategoryMacro_h
#define CategoryMacro_h

#ifdef __cplusplus
#define EXTERN_C_BEGIN  extern "C" {
#define EXTERN_C_END  }
#else
#define EXTERN_C_BEGIN
#define EXTERN_C_END
#endif

EXTERN_C_BEGIN

FOUNDATION_STATIC_INLINE NSString* NSNullText(id obj){
    return ([obj isKindOfClass:[NSString class]] ? obj : @"");
}

FOUNDATION_STATIC_INLINE NSNumber* NSNullNumber(id obj){
    return ([obj isKindOfClass:[NSNumber class]] ? obj : @0);
}

FOUNDATION_STATIC_INLINE NSArray* NSNullArray(id obj){
    return ([obj isKindOfClass:[NSArray class]] ? obj : @[]);
}

FOUNDATION_STATIC_INLINE NSDictionary* NSNullDict(id obj){
    return ([obj isKindOfClass:[NSDictionary class]] ? obj : @{});
}

FOUNDATION_STATIC_INLINE BOOL NSStringIsEmpty(NSString *string){
    if (string == nil || string.length == 0) {
        return YES;
    }
    return NO;
}

FOUNDATION_STATIC_INLINE BOOL NSDictionaryIsEmpty(NSDictionary *dictionary){
    if (dictionary && dictionary.count > 0 ) return NO;
    return YES;
}

FOUNDATION_STATIC_INLINE BOOL NSArrayIsEmpty(NSArray *array){
    if (array && array.count > 0 ) return NO;
    return YES;
}

/**
 测试方法调用时间
 */
FOUNDATION_STATIC_INLINE void ProfileTime(void (^block)(void), void (^complete)(double ms)) {
    struct timeval t0, t1;
    gettimeofday(&t0, NULL);
    block();
    gettimeofday(&t1, NULL);
    double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_usec - t0.tv_usec) * 1e-3;
    complete(ms);
}

/**
 Ceil the rect (for string drawing calculate)
 */
FOUNDATION_STATIC_INLINE CGRect CGRectCeil(CGRect rect) {
    return CGRectMake(ceil(rect.origin.x), ceil(rect.origin.y), ceil(rect.size.width), ceil(rect.size.height));
}

/**
 Ceil the size (for string drawing calculate)
 */
FOUNDATION_STATIC_INLINE CGSize CGSizeCeil(CGSize size) {
    return CGSizeMake(ceil(size.width), ceil(size.height));
}

/**
 The Center of this rect.
 */
FOUNDATION_STATIC_INLINE CGPoint CGRectCenter(CGRect rect) {
    return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}

FOUNDATION_STATIC_INLINE bool dispatch_is_main_queue() {
    // pthread_main_np(void);
    return [NSThread isMainThread];
}

/**
 Submits a block for asynchronous execution on a main queue and returns immediately.
 */
FOUNDATION_STATIC_INLINE void dispatch_async_on_main_queue(void (^block)(void)) {
    if (pthread_main_np()) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

EXTERN_C_END

#endif
